#include <stdint.h>
#include <stdio.h>
#include <stm32f1xx_ll_rcc.h>
#include <stm32f1xx_ll_tim.h>
#include <stm32f1xx_ll_bus.h>

void bsp_rtimer_init(uint64_t freq) {
  uint64_t div = 36000000ul / freq - 1;
  LL_TIM_InitTypeDef tim_cfg;

  LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM2);

  LL_TIM_StructInit(&tim_cfg);

  tim_cfg.Prescaler = div;
  tim_cfg.ClockDivision = LL_TIM_CLOCKDIVISION_DIV2;

  LL_TIM_Init(TIM2, &tim_cfg);

  LL_TIM_EnableCounter(TIM2);
}

void bsp_rtimer_trigger(uint64_t t) {
  uint16_t tick = 0;
  if (t < 2) {
    t = 2;
  }
  LL_TIM_CC_DisableChannel(TIM2, LL_TIM_CHANNEL_CH1);
  LL_TIM_OC_InitTypeDef oc_cfg;
  LL_TIM_OC_StructInit(&oc_cfg);

  tick = LL_TIM_GetCounter(TIM2);
  oc_cfg.CompareValue = tick + t;
  LL_TIM_OC_Init(TIM2, LL_TIM_CHANNEL_CH1, &oc_cfg);
  LL_TIM_CC_EnableChannel(TIM2, LL_TIM_CHANNEL_CH1);

  LL_TIM_EnableIT_CC1(TIM2);
}